package validating

import (
	"fmt"
	"regexp"
)

const (
	formatEmail = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
	formatIP    = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$"
	// 只能有密码和数字组成, 6-20位
	formatPwd = "^(?=.*\\d)(?=.*[A-z])[\\da-zA-Z]{6,20}$"
	// 英文、数字、下划线6-20位字符
	formatName = "^[\\w\\_]{6,20}$"
)

var ValidateEmailFunc = func(s string) error {
	return validateFunc(s, formatEmail)
}

var ValidateIPFunc = func(s string) error {
	if s == "N/A" {
		return nil
	}
	return validateFunc(s, formatIP)
}

var ValidatePasswordFunc = func(s string) error {
	return validateFunc(s, formatPwd)
}

var ValidateUsername = func(s string) error {
	return validateFunc(s, formatName)
}

func validateFunc(s, format string) error {
	if regexp.MustCompile(format).MatchString(s) {
		return nil
	}
	return fmt.Errorf("not match the format")
}
